namespace Digitalmes.Common.Workflows;

/// <summary>
/// 流程构建器。
/// </summary>
public sealed class WorkflowBuilder(string name) : WorkflowStepBuilder(name)
{
    private readonly List<WorkflowStepBuilder> _steps = [];

    public string Version { get; init; } = "v1";

    /// <summary>
    /// 添加流程步骤。
    /// </summary>
    /// <typeparam name="TStep">流程步骤</typeparam>
    public WorkflowStepBuilder AddStepFromType<TStep>(string? name = null) where TStep : WorkflowStep
    {
        WorkflowStepBuilder<TStep> stepBuilder = new(name);

        return AddStep(stepBuilder);
    }

    /// <summary>
    /// 流程起始事件。
    /// </summary>
    /// <param name="eventId">要触发的事件名称。</param>
    /// <returns></returns>
    public WorkflowEdgeBuilder OnInputEvent(string eventId)
    {
        return new WorkflowEdgeBuilder(this, eventId);
    }

    /// <summary>
    /// 构建流程。
    /// </summary>
    public Workflow Build()
    {
        var builtEdges = Edges.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Select(e => e.Build()).ToList());
        Workflow workflow = new([], builtEdges);

        return workflow;
    }

    private TBuilder AddStep<TBuilder>(TBuilder builder) where TBuilder : WorkflowStepBuilder
    {
        // 不能重复注册步骤
        if (_steps.Select(step => step.Name).Contains(builder.Name))
        {
            throw new InvalidOperationException($"Step name {builder.Name} is already used, assign a different name for step");
        }

        _steps.Add(builder);

        return builder;
    }
}
